﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using MixScriptWeb.control;
using MixScriptWeb.Share;
using MixScript.BLL;
using MixScriptWeb.AppCode.gjips;
using MixScript.BLL.WM;
namespace MixScriptWeb.Jideco
{
    public partial class fSrtJalan : cCommonWeb2, IMIxCommon
    {
        private static DataTable dt;
        private static DataTable dtprint;
        private static SortDirection sd;
        private static cRefGjips oReff;
        private static string sDNTypel;
        

        // private static Control[] ctl;
        //private const string stblname = "vw_joid_delivery_notes_v";
        private static string stblname ="";

        private static string scustid, ddate = "";

        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {

                if (!Page.IsPostBack)
                {
                    addFindClickAttribute(this, new MixScriptTB[] { txtcustid }, new string[] { "SRCCUST" });
                    //txtItNo.ReadOnly = true;
                    //  setSortExpression(gvdetail, new string[] { "banknum", "bankname", "address", "city", "country", "ac" });


                    //txtcustid.Tbx.Attributes.Add("readonly", "readonly");
                    // addRead(new MixScriptTB[] { txtcustid });
                    txtDate1.CssClass += " ritonli";
                    //string[] sheadertext = new string[] { "Case No.", "Sales Slip No.", "Customer Type", "Customer Code", "Delivery Place", "Addressee", "Delivery Date", "Customer PO. No.", "Customer Part No.", "Part No.", "Packing Quantity", "Contract Unit Code", "Order No.", "Shipping Date" };
                    string[] sheadertext = new string[] { "Delivery Date", "Customer PO. No.", "Customer ID", "Part No", "Part Name", "Customer Name", "Address", "Quantity", "Unit","Case No"};
                    string[] sdatavalue = new string[] {  "dvdt", "cuslno","cuid", "oaitno", "itnm","bpidnm", "ad1" , "pkqt", "unmsns", "pkno"};
                    //string[] sdatavalue = new string[] { "pkno", "saslno", "cuidbc", "cuid", "cuiddvlc", "cuidadlc", "dvdt", "cuslno", "cuitno", "oaitno", "pkqt", "tdms", "cuod", "fpdt" };
                    initGvColumn(gvdetail, sheadertext, sdatavalue, new int[] {0}, "{0:dd-MM-yyyy}");
                    MultiView1.SetActiveView(View1);
                    btnCreateDN.Visible = false;
                }
                mn = (MainMenu2)this.Master;
                hideStatusBar();
                // oReff = new cReferences();
                // if(gvdetail.Rows.Count>0)


            }
            catch (Exception ex)
            {
                if (mn == null)
                {
                    mn = (MainMenu2)this.Master;
                }
                ShowStatusBar(ex.Message, msgType.msgError);
            }


        }

        protected void gvdetail_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {

                //oUM = new cUserManagement();

                if (gvdetail.SelectedIndex > -1)
                {
                  //  txtcustid.Text = gvdetail.SelectedRow.Cells[0].Text;
                    //txtwrhcode.Text = gvdetail.SelectedRow.Cells[2].Text;
                    //txtWrhName.Text = gvdetail.SelectedRow.Cells[3].Text;
                    //txtWrhDesc.Text = gvdetail.SelectedRow.Cells[4].Text;




                    //ini ngehapus &nbsp;
                   // removeNbsp(new MixScriptTB[] { txtcustid });


                }
            }
            catch (Exception ex)
            {

                ShowStatusBar(ex.Message);
            }
        }

        protected void gvdetail_Sorting(object sender, GridViewSortEventArgs e)
        {
            if (sd == SortDirection.Ascending)
            {
                sd = SortDirection.Descending;
            }
            else
            {
                sd = SortDirection.Ascending;
            }

            DataView dataView = new DataView(dt);
            dataView.Sort = e.SortExpression + " " + ShortDirection(sd);

            bindGridview(gvdetail, dataView);
        }

        protected void gvdetail_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {

            gvdetail.PageIndex = e.NewPageIndex;
            //gvdetail.DataBind();
            bindGridview(gvdetail, dt);


        }

        protected void btnFind_Click(object sender, EventArgs e)
        {
            try
            {
                if (txtcustid.Text.Trim() != string.Empty && txtDate1.Text.Trim() != string.Empty)
                {
                    
                    scustid = txtcustid.Text.ToUpper();
                    ddate = txtDate1.Text;
                    sDNTypel = (new cDN().getTipeDN(txtcustid.Text)).Trim();

                  if(sDNTypel.Trim()=="IND")
                  {
                      gvdn.Columns[5].Visible=true;
                      stblname = "vw_mapdnlocal";
                  }
                    else
                  {
                      stblname = "vw_mapdn";
                      gvdn.Columns[5].Visible=false;
                  }


                    oReff = new cRefGjips(); //new cUserManagement();
                    dt = new DataTable();
                    Control[] ctl = new Control[] {null, txtDate1, txtcustid };
                    if (oReff.getInquiry(ref dt, genInqParam(ctl), stblname, out errMsg))
                    {
                        btnCreateDN.Visible = true;
                    }
                    else
                    {
                        ShowStatusBar("Record Not Found", msgType.msgError);
                        btnCreateDN.Visible = false;
                    }
                    txtcustid.Text = txtcustid.Text.ToUpper();
                    bindGridview(gvdetail, dt);
                    

                }
                else
                {
                    ShowStatusBar("Custid and Delivery Date Must be filled");

                }

            }
            catch (Exception ex)
            {

                ShowStatusBar(ex.Message, msgType.msgError);
            }

        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                //oReff = new cReferences();
                //string ss = "";
                //if (isvalid())
                //{
                //    if (txtwrhid.Text.Trim() == string.Empty)
                //    {

                //        if (oReff.AddNewRowDB(out errMsg, "tb_wrhmst", new int[] { 0 }, new string[] { "WRHID" }, false, txtwrhid.Text, txtwrhcode.Text, txtWrhName.Text, txtWrhDesc.Text))
                //        {
                //            ShowStatusBar(errMsg, msgType.msgSuccess);
                //            txtwrhid.Text = ss;
                //            btnFind_Click(btnFind, new EventArgs());
                //            btnClear_Click(btnClear, new EventArgs());
                //        }
                //        else
                //        {
                //            ShowStatusBar(errMsg, msgType.msgError);
                //        }

                //    }
                //    else
                //    {
                //        if (oReff.isRecordExist("tb_wrhmst", new string[] { "wrhid" }, new object[] { txtwrhid.Text}))
                //        {
                //            if (oReff.EditRowDtDB(out errMsg, "tb_wrhmst", new string[] { "wrhid" }, new object[] { txtwrhid.Text }, false, txtwrhid.Text, txtwrhcode.Text, txtWrhName.Text, txtWrhDesc.Text))
                //            {
                //                ShowStatusBar(errMsg, msgType.msgSuccess);
                //                btnFind_Click(btnFind, new EventArgs());
                //                btnClear_Click(btnClear, new EventArgs());
                //            }
                //            else
                //            {
                //                ShowStatusBar(errMsg, msgType.msgError);
                //            }

                //        }
                //        else
                //        {
                //            ShowStatusBar("Record Not Found");
                //        }
                //    }
                //}
                //else
                //{
                //    // ShowStatusBar(errMsg);
                //}
            }
            catch (Exception ex)
            {

                ShowStatusBar(ex.Message);
            }
        }



        protected void btnDelete_Click(object sender, EventArgs e)
        {
            try
            {
                ////cek apakah user sudah pilih data yg akan dihapus
                //if (txtwrhid.Text != string.Empty)
                //{
                //    //cek apakah data itu ada
                //    if (oReff.isRecordExist("tb_wrhmst", new string[] { "wrhid" }, new object[] { txtwrhid.Text }))
                //    {
                //        oReff = new cReferences();

                //        //coba hapus
                //        //                                nama primary key                nilainya          nama tablenya   pesan error
                //        if (oReff.deleteRowDB(new string[] { "wrhid" }, new object[] { txtwrhid.Text }, "tb_wrhmst", out errMsg))
                //        {
                //            //jika berhasil
                //            ShowStatusBar(em.getError(8), msgType.msgSuccess);
                //        }
                //        else
                //        {   //jika gagal
                //            ShowStatusBar(errMsg);
                //        }

                //    }
                //    else
                //    {   //jika data tidak ditemukan
                //        ShowStatusBar(em.getError(7));
                //    }
                //}
                //else
                //{
                //    ShowStatusBar(em.getError(7));
                //}
            }
            catch (Exception ex)
            {

                ShowStatusBar(ex.Message);
            }
        }

        //protected void btnClear_Click(object sender, EventArgs e)
        //{
        //    try
        //    {

        //        if (dt.Rows != null)
        //        {
        //            Session["datareport"] = dt;
        //            Response.Redirect("~/tesreport.html");
        //        }
        //    }
        //    catch (Exception ex)
        //    {

        //        ShowStatusBar(ex.Message);
        //    }
        //    //try
        //    //{
        //    //    errMsg = "";
        //    //    setValid(new MixScriptTB[] { txtcustid });
        //    //    clearMixTB(new MixScriptTB[] { txtcustid });



        //    //}
        //    //catch (Exception ex)
        //    //{

        //    //    ShowStatusBar(ex.Message);
        //    //}

        //}



        #region IMIxCommon Members

        //validasi inputan
        public bool isvalid()
        {
            try
            {
                //errMsg = "";
                ////set semua control valid
                //setValid(new MixScriptTB[] { txtwrhid, txtwrhcode, txtWrhName, txtWrhDesc });
                ////cek semua field mandatory
                //if (MustFilledOk(new Control[] {  txtwrhcode, txtWrhName }, out errMsg))
                //{
                //    if (txtwrhcode.Text.Trim().Length == 3)
                //    {

                //    }
                //    else
                //    {
                //        ShowStatusBar(errMsg + " " + em.getError(15));
                //        return false;

                //    }

                //}
                //else
                //{
                //    ShowStatusBar(errMsg + " " + em.getError(2));
                //    return false;
                //}
                return true;
            }
            catch (Exception ex)
            {

                throw ex;
            }

        }

        #endregion




        #region Button





        #endregion


        #region Gridview
        #region Gridview Event





        protected void gvdetail_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            try
            {
                if (e.Row.DataItemIndex == -1)
                    return;
                e.Row.Attributes.Add("onMouseOver", "this.style.cursor='pointer';");
                e.Row.Attributes.Add("onclick", this.GetPostBackClientEvent(gvdetail, "Select$" + e.Row.RowIndex.ToString()));
                //e.Row.Attributes.Add("onclick", this.GetPostBackEventReference(gvdetail, "Select$" + e.Row.RowIndex.ToString())); //  (gvdetail, "Select$" + e.Row.RowIndex.ToString()));


            }
            catch (Exception ex)
            {

                ShowStatusBar(ex.Message);
            }
        }



        #endregion





        protected void btnReport_Click(object sender, EventArgs e)
        {
            try
            {

                if (dt.Rows != null)
                {
                    Session["datareport"] = dt;
                    Response.Redirect("~/tesreport.html");
                }
            }
            catch (Exception ex)
            {

                ShowStatusBar(ex.Message);
            }
        }
        protected void cbAll_CheckedChanged(object sender, EventArgs e)
        {
            try
            {
                bool b = ((CheckBox)sender).Checked;


                foreach (GridViewRow gr in gvdetail.Rows)
                {
                    CheckBox cb = (CheckBox)gr.Cells[0].FindControl("cbitem");
                    cb.Checked = b;
                }

            }
            catch (Exception ex)
            {

                ShowStatusBar(ex.Message);
            }
        }

        protected void btnCLear_Click1(object sender, EventArgs e)
        {
            try
            {
                txtcustid.Text = "";
                txtDate1.Text = "";
            }
            catch (Exception ex)
            {

                ShowStatusBar(ex.Message);
            }

        }

        protected void btnPrint_Click(object sender, EventArgs e)
        {

        }

        
        protected void btnCreateDN_Click(object sender, EventArgs e)
        {
            try
            {
               
                    //btnFind_Click(btnFind, new EventArgs());
                //cDN oDN = new cDN();
                //dtprint = new DataTable();
                //dtprint = oDN.getDeliveryNotePrint(scustid, ddate);
                if (sDNTypel == "IND")
                {
                    Label1.Text = "LOCAL";
                }
                else
                {
                    Label1.Text = "EXPORT";
                }
                int ic = 0;
                    if (dt.Rows.Count > 0)
                    {
                        int[] isel = getSelection(out ic);
                        //if (isel.Length > 0)
                        //{
                        //    //DataTable dttemp = new DataTable();
                        //    //DataColumnCollection dcl= dtprint.Columns;
                        //    //foreach (DataColumn dc in dcl)
                        //    //{
                        //    //    dttemp.Columns.Add(dc);
                        //    //}
                        //    int k = 0;
                        //    foreach (int c in isel)
                        //    {
                        //        dt.Rows.RemoveAt(c - k);
                        //        k += 1;
                        //    }

                        if (ic > 0)
                        {
                            for (int i = 0; i < dt.Rows.Count; i++)
                            {
                                dt.Rows[i][0] = i + 1;

                            }


                            MultiView1.SetActiveView(View2);
                            txtDelNo.Text = "JOID-DN-" +DateTime.Now.ToString("yy-MMdd-") +new cDN().getDElno();
                            gvdn.DataSource = dt;
                            gvdn.DataBind();
                        }
                        else
                        {
                            ShowStatusBar("Please Select Material First");
                        }
                    }
                    else
                    {
                        ShowStatusBar("Records not Found", msgType.msgWarning);
                    }

          
            }
               
            catch (Exception ex)
            {

                ShowStatusBar(ex.Message);
            }

        }

        private int[] getSelection(out int isel)
        {
            try
            {
                int[] i = new int[] { };
                isel = 0;
                List<int> li = new List<int>();
                int c = 0;
                int r=0;
                int irowcnt=dt.Rows.Count;
                foreach (GridViewRow gr in gvdetail.Rows)
                {
                    //if (c > 0)
                    //{
                        if (!((CheckBox)gr.Cells[0].FindControl("cbitem")).Checked)
                        {
                            li.Add(c);
                            dt.Rows.RemoveAt(c - r);
                            r += 1;
                        }
                        else //di tick
                        {
                            isel += 1;
                        }
                    //}
                    
                    c += 1;
                }

                if (irowcnt > 25)
                {
                           
                    for (int k = irowcnt - 25; k >0; k--)
                    {
                        dt.Rows.RemoveAt(isel);

                    }
                }
                
                return li.ToArray();
            }
            catch (Exception ex)
            {

                throw ex;
            }
        }
        protected void btnPrint_Click1(object sender, EventArgs e)
        {
            try
            {
                if (txtDelNo.Text.Trim() != string.Empty)
                {
                    txtDelNo.Text = txtDelNo.Text.ToUpper();
                    cDN odn = new cDN();
                    string sout = "";
                    int nret = 0;
                    int q=0;
                    string dntyp = "";
                    if (sDNTypel.Trim() == "IND")
                    {
                        foreach (GridViewRow gr in gvdn.Rows)
                        {
                            TextBox tb = (TextBox)gr.Cells[5].FindControl("tbSNP");
                            if (tb.Text != string.Empty)
                            {
                                dt.Rows[q]["snp"] = tb.Text;
                            }

                            q += 1;
                        }
                        dt.AcceptChanges();
                        dntyp = "L";
                    }
                    else
                    {
                        dntyp = "E";
                    }


                    if (!odn.saveDelNo(txtDelNo.Text, txtSNP.Text.Trim(), dntyp, ddlshowpo.SelectedValue, dt, out sout, txtcustid.Text.Trim()))
                    {
                        ShowStatusBar(sout, msgType.msgError);
                        
                    }

                    else
                    {
                        //Session["datareport"] = dt;
                        //Session["dntype"]=sDNTypel;
                       // Response.Redirect("~/print/dnno-" + txtDelNo.Text + ",dl.html");

                        string sscript = "";
                        sscript+= "<script>";
                        
                            sscript += "window.open('../print/rptid-1,dnno-" + txtDelNo.Text + ",dl.html', '_blank');";
                        
                        



                        sscript+="</script>";
                        ClientScript.RegisterStartupScript(GetType(), "report", sscript);
                        ShowStatusBar("Delivery Note has been created successfully", msgType.msgSuccess);
                     //   Response.Write("<script> window.open( '~/print/dl.html','_blank' ); </script>");
                      //  Response.Write("//sdfsdfdfs");
                    }
                    //  Response.Redirect("http://localhost:56680/print/dl.html");
                    //  ~/report/rptDN.aspx
                    // Response.Redirect("~/report/rptDN.aspx");


                }
                else
                {
                    ShowStatusBar("Delivery number must be filled");
                }

            }
            catch (Exception ex)
            {

                ShowStatusBar(ex.Message);
            }
        }

        protected void btnBack_Click(object sender, EventArgs e)
        {
            try
            {
                MultiView1.SetActiveView(View1);
            }
            catch (Exception ex)
            {

                throw;
            }
        }

        protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                if (ddldntyp.SelectedValue == "L")
                {
                    //lblsnp.Visible = true;
                    txtSNP.Visible = true;
                   // lblttk.Visible = true;
                }
                else
                {
                   // lblsnp.Visible = false;
                    txtSNP.Visible = false;
                   // lblttk.Visible = false;
                }
            }
            catch (Exception ex)
            {

                
            }
        }





        //protected void lbDelete_Click(object sender, EventArgs e)
        //{
        //    try
        //    {
        //        oReff = new cReferences();
        //        bool isok = true;
        //        int i = 0;
        //        foreach (GridViewRow gr in gvdetail.Rows)
        //        {

        //            if (((CheckBox)gr.Cells[0].FindControl("cbitem")).Checked)
        //            {
        //                string sid = gr.Cells[1].Text;

        //                if (!oReff.deleteRowDB(new string[] { "wrhid" }, new string[] { sid }, "tb_wrhmst", out errMsg))
        //                {
        //                    ShowStatusBar(em.getError(9) + sid + " " + errMsg);
        //                    isok = false;
        //                    continue;
        //                }
        //                else
        //                {
        //                    i++;
        //                }
        //            }

        //        }

        //        if (i == 0 && isok)
        //        {
        //            ShowStatusBar("Please Select Item First");
        //        }
        //        else if (isok)
        //        {
        //            btnClear_Click(this, new EventArgs());
        //            btnFind_Click(this, new EventArgs());
        //            ShowStatusBar("Delete Completed", msgType.msgSuccess);
        //        }
        //    }
        //    catch (Exception ex)
        //    {

        //        ShowStatusBar(ex.Message);
        //    }
        //}

        #endregion
    }
}